package com.huanghe.rabbitmq.work.lunxun;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException;

public class Worker1 {

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");

        Connection co = null;
        Channel channel = null;
        try {
            co = connectionFactory.newConnection("消费者");
            channel = co.createChannel();
            String queueName = "queue1";

            DeliverCallback deliver = new DeliverCallback() {
                @Override
                public void handle(String s, Delivery msg) throws UnsupportedEncodingException {
                    System.out.println("Worker1-收到消息" + new String(msg.getBody(), "UTF-8"));

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };

            //轮训 使用自动应答
            channel.basicConsume(queueName, true, deliver, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("发送失败");
                }
            });
            System.out.println("Worker1-开始接收消息");
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }

            if (co != null && co.isOpen()) {
                try {
                    co.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
